from sqlalchemy import Integer, String, Boolean, DateTime, Column, ForeignKey
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.db.base import Base
from datetime import datetime


class Resource(Base):
    __tablename__ = "resources"

    id: Mapped[str] = mapped_column(String(32), primary_key=True, index=True)
    name: Mapped[str] = mapped_column(String(50), unique=True, index=True, nullable=False)
    code: Mapped[str] = mapped_column(String(50), unique=True, index=True, nullable=False)
    type: Mapped[str] = mapped_column(String(50), nullable=False)  # api, menu, button, data
    path: Mapped[str] = mapped_column(String(255), nullable=True)  # API路径或菜单路径
    method: Mapped[str] = mapped_column(String(10), nullable=True)  # HTTP方法
    description: Mapped[str] = mapped_column(String(255), nullable=True)
    parent_id: Mapped[str] = mapped_column(String(32), ForeignKey('resources.id'), nullable=True)
    sort_order: Mapped[int] = mapped_column(Integer, default=0)
    created_at: Mapped[DateTime] = mapped_column(DateTime, default=datetime.now)
    updated_at: Mapped[DateTime] = mapped_column(DateTime, default=datetime.now, onupdate=datetime.now)
    tenant_id: Mapped[str] = mapped_column(String(32), ForeignKey('tenants.id'), nullable=False)
    
    # 添加与角色的多对多关系
    roles: Mapped[list["Role"]] = relationship(
        "Role",
        secondary="role_resource",
        back_populates="resources",
        lazy="selectin"
    )

    def __repr__(self):
        return f"<Resource(id='{self.id}', name='{self.name}', code='{self.code}')>"